#include "CDalOverlord.h"

#include <string>
#include <sstream>

#include "CDalRecord.h"

CDalOverlord::CDalOverlord()
{

}

CDalOverlord::~CDalOverlord()
{

}


/** @brief getLoginInfo
  *
  * @todo: document this function
  */
CDalRecord* CDalOverlord::getPlayerData(const char *username)
{
  std::string sql = "SELECT * FROM player WHERE username = '";
  sql += escape(username, '\'');
  sql += "'";
  return selectSql("lonserverdb", sql.c_str());
}

/** @brief getMinionDataByPlayerId
  *
  * @todo: document this function
  */
CDalRecord* CDalOverlord::getMinionDataByPlayerId(unsigned int player_id)
{
  std::ostringstream sout (std::ostringstream::out);
  sout << "SELECT * FROM minion WHERE owner_id = " << player_id;
  std::string sql = sout.str();

  return selectSql("lonserverdb", sql.c_str());
}

/** @brief insertPlayerData
  *
  * @todo: document this function
  */
bool CDalOverlord::insertPlayerData(const char *username,
                                    const char *password,
                                    const char *player_name,
                                    int overlord_type_code,
                                    int overlord_title_code,
                                    int fame ,
                                    int win_count ,
                                    int lose_count)
{
  // construct query
  std::ostringstream sout (std::ostringstream::out);
  sout << "INSERT INTO player(player_name, username, password, ";
  sout << "overlord_type_code, overlord_title_code, fame, win_count, ";
  sout << "lose_count) VALUES (";
  sout << "'" << escape(player_name, '\'')  << "', ";
  sout << "'" << escape(username, '\'')     << "', ";
  sout << "'" << escape(password, '\'')     << "', ";
  sout << overlord_type_code << ", ";
  sout << overlord_title_code << ", ";
  sout << fame << ", ";
  sout << win_count << ", ";
  sout << lose_count << ");";

  std::string sql = sout.str();
  return insertSql("lonserverdb", sql.c_str());
}

/** @brief updateGameResult
  *
  * @todo: document this function
  */
bool CDalOverlord::updateGameResult(unsigned int player_id, bool status)
{
  std::string field;
  if (status)
    field = "win_count";
  else
    field = "lose_count";

  // construct query
  std::ostringstream sout (std::ostringstream::out);
  sout << "UPDATE player ";
  sout << "SET " << field << " = " << field << " + 1 ";
  sout << "WHERE player_id = " << player_id;

  std::string sql = sout.str();

  return insertSql("lonserverdb", sql.c_str());
}

